package cn.zhy.basic.controller;

import cn.zhy.basic.util.AjaxResult;
import cn.zhy.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult upload(@RequestPart("file")MultipartFile file){

        try {
            //获取原始文件名  XXX.png
            String originalFilename = file.getOriginalFilename();
            //获取扩展名  png
            String exName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //调用工具类上传FastDfs
            // /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
            String fileName = FastDfsUtil.upload(file.getBytes(), exName);
            //把上传之后的路径响应给前端
            return AjaxResult.me().setResultObj(fileName);

        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败");
        }

    }


    /**
     * 文件删除
     * 将路径传过来
     * /group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg = path
     *  group1   M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam("path") String path){

        try {
            //将path里边group1前边的第一个/去掉
            String pathTemp = path.substring(1);
            //获取组名
            String groupName = pathTemp.substring(0,pathTemp.indexOf("/"));
            //获取文件名
            String fileName = pathTemp.substring(pathTemp.indexOf("/")+1);
            FastDfsUtil.delete(groupName,fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }



}
